const { Telegraf, Markup, Composer, Scenes, session } = require("telegraf");
const { searchOnboarding, loggerMidlware, logger } = require("./googleAuth.js");
const { TELEGRAM_API_TOKEN } = process.env;
const bot = new Telegraf(TELEGRAM_API_TOKEN, {
  polling: {
    interval: 300,
    autoStart: true,
  },
});

const registration = new Scenes.WizardScene(
  "registration",
  (ctx) => {
    ctx.reply("Введите пароль");
    return ctx.wizard.next(); // Proceed to the next step
  },
  (ctx) => {
    ctx.reply("Введите ФИО полностью");
    if (ctx.message.text === "Detmir") {
      return ctx.wizard.next();
    } else {
      ctx.reply("Ошибка");
      ctx.scene.leave();
    }
  },
  async (ctx) => {
    await logger(ctx.message.text, ctx.from.id);
    ctx.reply("Отлично, нажмите /start");
    ctx.scene.leave();
    // Proceed to the next step
  }
  // (ctx) => {
  //   ctx.reply("Отлично, нажмите /start");
  //   ctx.scene.leave(); // Proceed to the next step
  // }
);

const stage = new Scenes.Stage([registration]);

bot.use(session());
bot.use(stage.middleware());

bot.command("reg", (ctx) => {
  ctx.scene.enter("registration");
});

bot.command(
  "start",
  loggerMidlware,

  async (ctx) => {
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth() + 1;
    const daysInMonth = new Date(currentYear, currentMonth, 0).getDate();
    const today = currentDate.getDate() + 2;
    const buttons = [];

    for (let day = today; day <= daysInMonth; day++) {
      addButton(buttons, day, currentMonth, currentYear, "День", "Day");
      addButton(buttons, day, currentMonth, currentYear, "Ночь", "Night");
    }
    const dayDifference = daysInMonth - today;
    if (dayDifference < 13) {
      const nextCurrentMonth = currentMonth + 1 === 13 ? 1 : currentMonth + 1;
      const nextCurrentYear =
        currentMonth + 1 === 13 ? currentYear + 1 : currentYear;

      for (let day = 1; day <= 13 - dayDifference; day++) {
        addButton(
          buttons,
          day,
          nextCurrentMonth,
          nextCurrentYear,
          "День",
          "Day"
        );
        addButton(
          buttons,
          day,
          nextCurrentMonth,
          nextCurrentYear,
          "Ночь",
          "Night"
        );
      }
    }

    addButtonEnd(buttons, "Отправить", "Отправить");

    const keyboard = Markup.inlineKeyboard(buttons, { columns: 2 }).resize();
    ctx.reply("Выбери дату и время выхода на смену:", keyboard);
  }
);

function addButtonEnd(buttons, send, calback) {
  buttons.push(Markup.button.callback(`${send}`, `${calback}`));
}
function addButton(buttons, day, month, year, time, postfix) {
  buttons.push(
    Markup.button.callback(
      `${day}.${month} ${time}`,
      `${day}.${month}.${year} (${postfix})`
    )
  );
}

bot.action(/^\d{1,2}\.\d{1,2}\.\d{4} \(Day\)$/, (ctx) => {
  const buttons = ctx.callbackQuery.message.reply_markup.inline_keyboard;
  for (let row of buttons) {
    for (let button of row) {
      if (button.callback_data === ctx.match[0]) {
        if (button.text.includes("✅")) {
          button.text = button.text.replace(" ✅", "");
        } else {
          button.text = button.text + " ✅";
        }
      }
    }
  }
  const updatedKeyboard = Markup.inlineKeyboard(buttons, {
    columns: 2,
  }).resize();
  ctx.editMessageText("Выбери дату и время выхода на смену:", updatedKeyboard);
});

bot.action(/^\d{1,2}\.\d{1,2}\.\d{4} \(Night\)$/, (ctx) => {
  const buttons = ctx.callbackQuery.message.reply_markup.inline_keyboard;
  for (let row of buttons) {
    for (let button of row) {
      if (button.callback_data === ctx.match[0]) {
        if (button.text.includes("✅")) {
          button.text = button.text.replace(" ✅", "");
        } else {
          button.text = button.text + " ✅";
        }
      }
    }
  }
  const updatedKeyboard = Markup.inlineKeyboard(buttons, {
    columns: 4,
  }).resize();
  ctx.editMessageText("Выбери дату и время выхода на смену:", updatedKeyboard);
});

bot.action("Отправить", (ctx) => {
  searchOnboarding(ctx);
  const buttons = ctx.callbackQuery.message.reply_markup.inline_keyboard;
  const modifiedArray = buttons.reduce((result, buttonRow) => {
    const dates = buttonRow.filter((button) => button.text.includes("✅"));
    const dateMap = new Map();

    for (const button of dates) {
      const buttonText = button.text.split(" ")[0];
      const dateTime = button.callback_data.includes("Night")
        ? buttonText + " Ночь"
        : buttonText + " День";

      if (!dateMap.has(buttonText) || dateTime.includes("Ночь")) {
        dateMap.set(buttonText, dateTime);
      }
    }

    result.push(...dateMap.values());

    return result;
  }, []);
  ctx.deleteMessage();
  console.log(modifiedArray);
  ctx.reply(`Дата выхода на смену:\n${modifiedArray.join("\n")}`);
});

bot.launch();
process.once("SIGINT", () => bot.stop("SIGINT"));
process.once("SIGTERM", () => bot.stop("SIGTERM"));
